/**
 * Copyright: Copyright (c)2015
 * Company: niuwap2p
 */
package com.niuwa.p2p.service.impl.borrowinfomg.enterpriseinfomg;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.utils.DateUtil;
import com.niuwa.p2p.core.utils.DictConstant;
import com.niuwa.p2p.dao.borrowinfomg.enterpriseinfomg.IEnterpriseinfoMgDao;
import com.niuwa.p2p.dao.channel.CorpContactorDao;
import com.niuwa.p2p.dao.channel.CorpManagerDao;
import com.niuwa.p2p.dao.channel.CorpShareHolderDao;
import com.niuwa.p2p.dao.channel.CorporationDao;
import com.niuwa.p2p.dao.channel.ManagerRelativeCorpDao;
import com.niuwa.p2p.dao.channel.ShareHolderDao;
import com.niuwa.p2p.entity.channel.CorpContactor;
import com.niuwa.p2p.entity.channel.CorpManager;
import com.niuwa.p2p.entity.channel.CorpShareHolder;
import com.niuwa.p2p.entity.channel.Corporation;
import com.niuwa.p2p.entity.channel.ManagerRelativeCorp;
import com.niuwa.p2p.entity.channel.ShareHolder;
import com.niuwa.p2p.exception.BusinessException;
import com.niuwa.p2p.service.borrowinfomg.enterpriseinfomg.IEnterpriseBasicInfoMgService;
import com.niuwa.p2p.service.sequence.ISequenceService;
import com.niuwa.p2p.vo.borrowinfomg.enterpriseinfomg.CorpBasicInfoVo;

/**
 * @author Jinchao
 * @date 2015年4月22日
 * @version 1.0
 */
@Service
public class EnterpriseBasicInfoMgServiceImpl implements IEnterpriseBasicInfoMgService {

	@Autowired
	private ISequenceService sequenceService;
	@Autowired
	private CorporationDao corporationDao;
	@Autowired
	private ShareHolderDao shareHolderDao;
	@Autowired
	private CorpShareHolderDao corpShareHolderDao;
	@Autowired
	private CorpManagerDao corpManagerDao;
	@Autowired
	private ManagerRelativeCorpDao managerRelativeCorpDao;
	@Autowired
	private CorpContactorDao corpContactorDao;
	@Autowired
	private IEnterpriseinfoMgDao enterpriseinfoMgDao;

	/**
	 * 添加企业基本信息
	 * 
	 * @throws Exception
	 */
	@Override
	public String addNewCorpBasicInfo(CorpBasicInfoVo cbiv) throws Exception {
		long seq = sequenceService.getNextSequenceBySeqKey(DictConstant.ChannelIdType.GSXX.getCode());
		Corporation corporation = cbiv.getCorporation();

		// 转换金额
		cbiv.getCorporation().setRegAmount(getWan(cbiv.getCorporation().getRegAmount()));
		List<ShareHolder> shareHolders = cbiv.getShareHolder();
		// 原始的corpShareHolder,需要进行转化...
		List<CorpShareHolder> corpShareHolders = cbiv.getCorpShareHolder();

		Date currDate = new Date();
		String corpCode = "F" + DateUtil.getYear(currDate) + DateUtil.getMonth(currDate) + String.format("%04d", seq);

		// 公司编号与渠道编号一致
		corporation.setCorpCode(corpCode);
		corporation.setCreateTime(new Date());
		corporation.setAuditStatus(DictConstant.ChlOperAuditType.EDIT.getCode());
		corporation.setDelFlag(DictConstant.DEL_FLAG.DEL_N.getCode());

		corporationDao.insert(corporation);

		for (int i = 0; i < shareHolders.size(); i++) {
			if (StringUtils.isBlank(shareHolders.get(i).getShareholderName())) {
				// 股东名称为空 不保存
				// shareHolders.remove(i);
				continue;
			}
			// 判断类型
			long seq2 = sequenceService.getNextSequenceBySeqKey(DictConstant.ChannelIdType.GDXX.getCode());

			String shareHolderCode = corpCode + "S" + String.format("%03d", seq2);
			shareHolders.get(i).setShareholderCode(shareHolderCode);
			// covert regAmount
			BigDecimal regAmount = shareHolders.get(i).getRegAmount();
			if (regAmount != null) {
				shareHolders.get(i).setRegAmount(regAmount.multiply(new BigDecimal(10000)));
			}
			corpShareHolders.get(i).setCorpCode(corpCode);
			corpShareHolders.get(i).setShareholderCode(shareHolderCode);

			shareHolderDao.insert(shareHolders.get(i));
			corpShareHolderDao.insert(corpShareHolders.get(i));
		}

		// 保存法人数据
		CorpManager legalMan = cbiv.getLegalMan();
		if (StringUtils.isNotBlank(legalMan.getName())) {
			saveCorpManager(legalMan, corpCode, "LEGAL_MAN");
		}

		// 设置总经理数据 XiangChaoLei
		CorpManager generalManager = cbiv.getGeneralManager();
		if (StringUtils.isNotBlank(generalManager.getName())) {
			saveCorpManager(legalMan, corpCode, "GENERAL_MANAGER");
		}

		// 保存联系人信息 XiangChaoLei
		for (int i = 0; i < cbiv.getCorpContactor().size(); i++) {
			CorpContactor corpContactor = cbiv.getCorpContactor().get(i);
			if (StringUtils.isBlank(corpContactor.getContactor())) {
				continue;
			}
			corpContactor.setCorpCode(corpCode);
			corpContactor.setCreateTeme(new Date());
			corpContactorDao.insert(corpContactor);
		}
		// 保存联系人信息end
		return corpCode;
	}

	@Override
	public int updateEnterpirseInfo(CorpBasicInfoVo cbiv) throws Exception {

		int result = 0;
		CorpBasicInfoVo oldCbiv = getCorpBasicInfo(cbiv.getCorporation().getCorpCode());

		String corpCode = oldCbiv.getCorporation().getCorpCode();

		// 转换申请金额
		cbiv.getCorporation().setRegAmount(getWan(cbiv.getCorporation().getRegAmount()));

		// 更新公司基本信息
		result = corporationDao.updateByPrimaryKeySelective(cbiv.getCorporation());
		if (result != 1) {
			throw new BusinessException("EnterpriseBasicInfoMgService.failTOUpdateBasicCorpInfo");
		}

		// 更新股东信息
		List<ShareHolder> newShs = cbiv.getShareHolder();
		List<CorpShareHolder> newCsh = cbiv.getCorpShareHolder();

		List<ShareHolder> oldShs = oldCbiv.getShareHolder();
		List<CorpShareHolder> oldCsh = oldCbiv.getCorpShareHolder();

		HashMap<String, ShareHolder> shareHolderKeys = new HashMap<String, ShareHolder>();
		HashMap<String, CorpShareHolder> corpShareHolderKeys = new HashMap<String, CorpShareHolder>();

		for (int i = 0; i < oldShs.size(); i++) {
			shareHolderKeys.put(oldShs.get(i).getShareholderCode(), oldShs.get(i));
			corpShareHolderKeys.put(oldCsh.get(i).getShareholderCode(), oldCsh.get(i));
		}

		for (int i = 0; i < newShs.size(); i++) {

			BigDecimal regAmount = newShs.get(i).getRegAmount();
			if (regAmount != null) {
				newShs.get(i).setRegAmount(regAmount.multiply(new BigDecimal(10000)));
			}

			if (shareHolderKeys.containsKey(newShs.get(i).getShareholderCode())) {
				// update
				result = shareHolderDao.updateByPrimaryKey(newShs.get(i));
				if (result != 1) {
					throw new BusinessException("EnterpriseBasicInfoMgService.failTOUpdateBasicCorpInfo");
				}

				newCsh.get(i).setShareholderCode(newShs.get(i).getShareholderCode());
				newCsh.get(i).setCorpCode(cbiv.getCorporation().getCorpCode());
				result = corpShareHolderDao.updateByPrimaryKey(newCsh.get(i));
				if (result != 1) {
					throw new BusinessException("EnterpriseBasicInfoMgService.failTOUpdateBasicCorpInfo");
				}
				shareHolderKeys.remove(newShs.get(i).getShareholderCode());
				corpShareHolderKeys.remove(newShs.get(i).getShareholderCode());
			} else {
				// insert, 增加相应字段...
				long seq2 = sequenceService.getNextSequenceBySeqKey(DictConstant.ChannelIdType.GDXX.getCode());

				String shareHolderCode = corpCode + "S" + String.format("%03d", seq2);
				newShs.get(i).setShareholderCode(shareHolderCode);
				newCsh.get(i).setCorpCode(corpCode);
				newCsh.get(i).setShareholderCode(shareHolderCode);

				result = shareHolderDao.insert(newShs.get(i));
				if (result != 1) {
					throw new BusinessException("EnterpriseBasicInfoMgService.failTOUpdateBasicCorpInfo");
				}
				result = corpShareHolderDao.insert(newCsh.get(i));

				if (result != 1) {
					throw new BusinessException("EnterpriseBasicInfoMgService.failTOUpdateBasicCorpInfo");
				}
			}
			if (result != 1) {
				throw new BusinessException("EnterpriseBasicInfoMgService.failTOUpdateBasicCorpInfo");
			}
		}

		// delete all the delete info
		Iterator<Entry<String, ShareHolder>> iter = shareHolderKeys.entrySet().iterator();
		while (iter.hasNext()) {

			ShareHolder val = iter.next().getValue();
			result = shareHolderDao.deleteByPrimaryKey(val.getShareholderCode());
			if (result != 1) {
				throw new BusinessException("EnterpriseBasicInfoMgService.failTOUpdateBasicCorpInfo");
			}
		}
		Iterator<Entry<String, CorpShareHolder>> iter2 = corpShareHolderKeys.entrySet().iterator();
		while (iter2.hasNext()) {
			CorpShareHolder val = iter2.next().getValue();
			result = corpShareHolderDao.deleteByPrimaryKey(val);
			if (result != 1) {
				throw new BusinessException("EnterpriseBasicInfoMgService.failTOUpdateBasicCorpInfo");
			}
		}

		// 更新法人数据
		CorpManager legalMan = cbiv.getLegalMan();
		if (oldCbiv.getLegalMan() == null) {
			saveCorpManager(legalMan, corpCode, "LEGAL_MAN");
		} else {
			legalMan.setManagerCode(oldCbiv.getLegalMan().getManagerCode());
			result = corpManagerDao.updateByPrimaryKey(legalMan);
			if (result != 1) {
				throw new BusinessException("EnterpriseBasicInfoMgService.failTOUpdateBasicCorpInfo");
			}
		}
		// 更新法人数据end

		// 更新总经理数据
		CorpManager generalManager = cbiv.getGeneralManager();
		if (oldCbiv.getGeneralManager() == null) {
			saveCorpManager(legalMan, corpCode, "GENERAL_MANAGER");
		} else {
			generalManager.setManagerCode(oldCbiv.getGeneralManager().getManagerCode());
			result = corpManagerDao.updateByPrimaryKey(generalManager);
			if (result != 1) {
				throw new BusinessException("EnterpriseBasicInfoMgService.failTOUpdateBasicCorpInfo");
			}
		}
		// 更新总经理数据end

		// 保存联系人信息
		Map<String, CorpContactor> conts = new HashMap<String, CorpContactor>();

		for (int i = 0; i < oldCbiv.getCorpContactor().size(); i++) {
			CorpContactor corpContactor = oldCbiv.getCorpContactor().get(i);
			conts.put(corpContactor.getContactor(), corpContactor);
		}

		for (CorpContactor c : cbiv.getCorpContactor()) {
			if(StringUtils.isNotBlank(c.getContactor())){
				if (conts.containsKey(c.getContactor())) {
					result = corpContactorDao.updateByPrimaryKeySelective(c);
					conts.remove(c.getContactor());
				} else {
					c.setCorpCode(corpCode);
					c.setCreateTeme(new Date());
					result = corpContactorDao.insert(c);
				}
			}
		}
		
		for(CorpContactor cc : conts.values()){
			corpContactorDao.deleteByPrimaryKey(cc.getId());
		}
		// 保存联系人信息end
		return result;
	}

	/**
	 * 取得企业基本信息
	 * 
	 * @param channelCode 业务编号
	 * @return ChannelBasicInfoVo 渠道基本信息
	 */
	public CorpBasicInfoVo getCorpBasicInfo(String corpCode) {
		return enterpriseinfoMgDao.selectCorpBasicInfoByChannelCode(corpCode);
	}

	/**
	 * 保存corpManger
	 * 
	 * @param manager
	 * @param corpCode
	 * @param manageType
	 * @throws Exception
	 */
	private void saveCorpManager(CorpManager manager, String corpCode, String manageType) throws Exception {
		long generalManagerSeq = sequenceService.getNextSequenceBySeqKey(DictConstant.ChannelIdType.JLXX.getCode());
		String generalManagerCode = corpCode + "M" + String.format("%03d", generalManagerSeq);
		manager.setManagerCode(generalManagerCode);
		manager.setCreateTime(new Date());
		ManagerRelativeCorp generalManagerRela = new ManagerRelativeCorp();
		generalManagerRela.setCorpCode(corpCode);
		generalManagerRela.setManagerCode(generalManagerCode);
		generalManagerRela.setManagerType(manageType);
		// 设置总经理数据end

		corpManagerDao.insert(manager);
		managerRelativeCorpDao.insert(generalManagerRela);
	}

	@Override
	public Corporation getCorpByName(String corpName) {
		return corporationDao.selectByCorpName(corpName);
	}

	/**
	 * 金额转换为以万为单位
	 * 
	 * @param b 原金额 可以为
	 * @return null or b * 10000
	 */
	private BigDecimal getWan(BigDecimal b) {
		if (b == null) {
			return null;
		} else {
			return b.multiply(new BigDecimal(10000));
		}
	}
}
